package com.gongpingjialoan.activity.car;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.Toast;

import com.gongpingjialoan.R;
import com.gongpingjialoan.activity.fb.MyPushIntentService;
import com.gongpingjialoan.activity.main.BaseActivity;
import com.gongpingjialoan.activity.main.LoginActivity;
import com.gongpingjialoan.activity.main.MainActivity;
import com.gongpingjialoan.api.API;
import com.gongpingjialoan.bean.Monitor;
import com.gongpingjialoan.global.GPJApplication;
import com.gongpingjialoan.network.NetDataJson;
import com.gongpingjialoan.receiver.AddLikeBoardCast;
import com.gongpingjialoan.utility.StepMonitor;
import com.gongpingjialoan.utility.StepRecord;
import com.gongpingjialoan.widget.LoadingDialog;
import com.handmark.pulltorefresh.library.smarttablayout.SmartTabLayout;

import org.json.JSONException;
import org.json.JSONObject;

public class DiscountDetailActivity extends BaseActivity implements  NetDataJson.OnNetDataJsonListener {

    private ImageView report_View;

    private ViewPager viewPager;

    private NetDataJson mNetCarDetail;

    private LoadingDialog loadingDialog = null;

    private String mProductId;

    private String fromType;

    private int currentItem = 0 ;

    private static final int LOGINING = 0X0392;

    private NetDataJson collectNetDataJson;

    private SmartTabLayout tabLayout;

    private SecondCarFragment secondCarFragment;

    private NewCarParametsFragment newCarParametsFragment;

    private boolean isLike = false;

    private String[] actions = {"recommend_detail", "recommend_detail_newConfig"};

    private String[] titles = {"二手车详情", "新车配置"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.discount_detail);
        fromType = getIntent().getStringExtra("type");
        setTitle("限时促销详情");

        //activity被回收执行
        if (savedInstanceState != null) {
            secondCarFragment = (SecondCarFragment) getSupportFragmentManager().findFragmentByTag("android:switcher:" + R.id.view_pager + ":0");
            newCarParametsFragment = (NewCarParametsFragment) getSupportFragmentManager().findFragmentByTag("android:switcher:" + R.id.view_pager + ":1");
        } else {
            secondCarFragment = new SecondCarFragment();
            newCarParametsFragment = new NewCarParametsFragment();
        }
        initView();
        initData();
        initLinister();
    }


    @Override
    public void onResume() {
        super.onResume();
        StepMonitor.getInstance().addMonitor(new Monitor("enter", actions[currentItem], System.currentTimeMillis(), 1f));
    }

    private void initView() {

        loadingDialog = new LoadingDialog(this, "加载中...");
        // loadingDialog.show();
        report_View = (ImageView) findViewById(R.id.right_img);


        tabLayout = (SmartTabLayout) findViewById(R.id.tableLayout);

        viewPager = (ViewPager) this.findViewById(R.id.view_pager);
        viewPager.setAdapter(new DisCountAdapter(getSupportFragmentManager()));
        tabLayout.setViewPager(viewPager);
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                currentItem = position;
                StepMonitor.getInstance().addMonitor(new Monitor("enter", actions[currentItem], System.currentTimeMillis(), 1f));
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

    }

    private void initData() {
        Bundle bundle = getIntent().getExtras();
        //推送用
        String source = bundle.getString("source", "");
        String job_id = bundle.getString("job_id", "");

        mProductId = bundle.getString("typevalue");

        if (MyPushIntentService.PROMOTIONDETAIL.equals(fromType)) {
            StepRecord.recordStep(this, "pushnotification", "{type:" + fromType + ",typevalue:" + mProductId + ",source:"  + source + ",job_id:"  + job_id + "}");
        }

        loadingDialog.show();
        mNetCarDetail = new NetDataJson(this);
        mNetCarDetail.setUrl(API.discountDetails);
        mNetCarDetail.addParam("promo_car_id", mProductId);
        mNetCarDetail.addParam("device_code", GPJApplication.getInstance().getDeviceCode());
        mNetCarDetail.request("get");
    }


    @Override
    public void onBackPressed() {
        //表示从推送而来
        if (MyPushIntentService.PROMOTIONDETAIL.equals(fromType)) {
            Intent intent = new Intent(this, MainActivity.class);
            startActivity(intent);
            finish();
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public void initTitleBar() {
        View backV = findViewById(R.id.title_back);
        if (backV != null) {
            backV.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View arg0) {
                    onBackPressed();
                }
            });
        }
    }


    public void report() {
        if (GPJApplication.getInstance().isLogin()) {
            Intent intent = new Intent(this, ReportActivity.class);
            intent.putExtra("promo_car_id", mProductId);
            startActivity(intent);
        } else {
            Intent intent = new Intent(this, LoginActivity.class);
            intent.putExtra("isRefreshDiscountCar", false);
            startActivityForResult(intent, LOGINING);
        }

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent arg2) {
        super.onActivityResult(requestCode, resultCode, arg2);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == LOGINING) {
                Intent intent = new Intent(this, ReportActivity.class);
                intent.putExtra("promo_car_id", mProductId);
                startActivity(intent);
            }
        }
    }


    class DisCountAdapter extends FragmentPagerAdapter {

        public DisCountAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int arg0) {
            switch (arg0) {
                case 0:
                    return secondCarFragment;
                case 1:
                    return newCarParametsFragment;
                default:
                    break;
            }
            return null;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return titles[position];
        }

        @Override
        public int getCount() {
            return 2;
        }

    }


    @Override
    public void onDataJsonError(String errorMessage) {
        loadingDialog.dismiss();
        Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT).show();
    }


    @Override
    public void onDataJsonUpdate(JSONObject json) {
        try {
            isLike = json.getBoolean("is_liked");

            report_View.setVisibility(View.GONE);
            if (isLike)
                report_View.setBackgroundResource(R.drawable.collect_y);
            else
                report_View.setBackgroundResource(R.drawable.collect_n);
        } catch (JSONException e) {
        }
        secondCarFragment.loadDataSuccess(json);
        newCarParametsFragment.loadDataSuccess(json);
        loadingDialog.dismiss();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mNetCarDetail != null) {
            mNetCarDetail.cancelTask();
            mNetCarDetail = null;
        }
        if (collectNetDataJson != null) {
            collectNetDataJson.cancelTask();
            collectNetDataJson = null;
        }
    }



    private void sendCollectChange(){
        Intent intent = new Intent(AddLikeBoardCast.ADD_REMOVE_LIKE);
        sendBroadcast(intent);
    }

    //收藏接口
    private void initLinister() {
        report_View.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                StepMonitor.getInstance().addMonitor(new Monitor("click" , "recommend_detail_like" , System.currentTimeMillis() , 1f));
                loadingDialog.show();
                if (!isLike) {
                    collectNetDataJson = new NetDataJson(new NetDataJson.OnNetDataJsonListener() {
                        @Override
                        public void onDataJsonError(String errorMessage) {
                            loadingDialog.dismiss();
                            Toast.makeText(getApplicationContext(), errorMessage, Toast.LENGTH_SHORT).show();
                        }

                        @Override
                        public void onDataJsonUpdate(JSONObject json) {

                            loadingDialog.dismiss();
                            isLike = true;
                            Toast.makeText(getApplicationContext(), "收藏成功！", Toast.LENGTH_SHORT).show();
                            report_View.setBackgroundResource(R.drawable.collect_y);
                            sendCollectChange();
                        }
                    });
                    collectNetDataJson.addParam("promo_car_id", mProductId);
                    collectNetDataJson.setUrl(API.collectCars);
                    collectNetDataJson.request("post");
                } else {
                    collectNetDataJson = new NetDataJson(new NetDataJson.OnNetDataJsonListener() {
                        @Override
                        public void onDataJsonError(String errorMessage) {
                            loadingDialog.dismiss();
                            Toast.makeText(getApplicationContext(), errorMessage, Toast.LENGTH_SHORT).show();
                        }

                        @Override
                        public void onDataJsonUpdate(JSONObject json) {
                            loadingDialog.dismiss();
                            isLike = false;
                            Toast.makeText(getApplicationContext(), "取消收藏成功！", Toast.LENGTH_SHORT).show();
                            report_View.setBackgroundResource(R.drawable.collect_n);
                            sendCollectChange();
                        }
                    });
                    collectNetDataJson.addParam("ids", mProductId);
                    collectNetDataJson.addParam("record_type", "like_car");
                    collectNetDataJson.setUrl(API.deleteCollectCar);
                    collectNetDataJson.request("post");
                }
            }
        });

    }


}
